package com.v587888.day20171018;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class HelloWorldHex {

	public static void main(String[] args) throws IOException {
		FileInputStream fis = null;
		try {
			File file = new File(HelloWorldHex.class.getResource("HelloWorld.class").getPath());
			fis = new FileInputStream(file);
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			System.out.println(formatHex(bytesToHexString(buffer)));
		} finally {
			fis.close();
		}
	}
	
	/**
	* 字节码转hex
	* @title: bytesToHexString
	* @param src
	* @return 
	* @Author: zhaoweiyong
	* @Date: 2017年10月18日下午3:08:03
	*/
	public static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}
	
	/**
	* 格式化hex
	* @title: formatHex
	* @param hex
	* @return 
	* @Author: zhaoweiyong
	* @Date: 2017年10月18日下午3:08:22
	*/
	private static String formatHex(String hex) {
		StringBuilder result = new StringBuilder();
		for (int i = 0; i < hex.length(); i++) {
			char item = hex.charAt(i);
			result.append(String.valueOf(item));
			if (i % 2 == 1) {
				result.append("  ");
			}
			if (i > 30 && (i + 1) % 32 == 0) {
				result.append("\n");
			}
		}
		return result.toString();
	}

	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}

	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}
}
